package com.cmfi.schedule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.cmfi.dao.EnergyRecDao;
import com.cmfi.domain.EnergyRec;
import com.cmfi.event.SpringBootApplicationListener;
import com.cmfi.utils.OpcUaUtil;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Component
public class ScheduleService {
	 static Logger logger = LoggerFactory.getLogger(ScheduleService.class);
	 @Autowired
	 private SpringBootApplicationListener springBootApplicationListener;
	 @Autowired
	 private EnergyRecDao energyRecDao;
	 public double dailyTotal = 0;
	 public double lastDayTotal = 0;
	 EnergyRec energyRec = new EnergyRec();
	 
//	@Scheduled(cron="0/5 * * * * *")
//    public void schedule1() {
//    	//test
//		logger.info("test ScheduleService-----------------------------");
//		//log.info()----需要安装lombok插件
//    }
//	
	 @Scheduled(fixedRate=100000000)//此时长为测试时避免出现大量报错用，现场调试需要修改为实际需要时间
	    public void schedule2() {
//			List<NodeId> list = new ArrayList<>();
//			List<DataValue> opcuaList = new ArrayList<>();		
//			NodeId nodeId = new NodeId(3, "energy");//点位要动态获取
//			list.add(nodeId);
//			try {
//				if (springBootApplicationListener.client != null) {
//					opcuaList = OpcUaUtil.readNodeMulti(springBootApplicationListener.client, list);
//					}//由于只有1个点位，取list[0],getValue中再来一个getValue？
//				DataValue variant = opcuaList.get(0);//取list中第0条数据来处理
//				double value = Double.parseDouble(variant.getValue().toString());//string强转double
//				dailyTotal = value - lastDayTotal;//当前日期当前时间累计使用能源总量
//				Calendar now = Calendar.getInstance();
//				
//				//每小时存一条电表数据
//				if (now.get(Calendar.MINUTE) == 0 && now.get(Calendar.SECOND) == 0) {
//			    	energyRec.setValue(dailyTotal);//当时的每日用量
//			    	energyRec.setCreateTime(Instant.now());//日期1
//			    	energyRecDao.save(energyRec);//保存上述信息
//			        }
//				
//			    // 检查当前时间是否为午夜00:00,最好设定一个误差范围，否则很容易出问题
//			    if (now.get(Calendar.HOUR_OF_DAY) == 0 && now.get(Calendar.MINUTE) == 0 && now.get(Calendar.SECOND) == 0) {
//			    	energyRec.setValue(dailyTotal);//当时读到的电表读数
//			    	energyRec.setLastDay(dailyTotal);//将本日使用的能量总数存入数据库
//			    	energyRec.setCreateTime(Instant.now());//日期2
//			    	energyRecDao.save(energyRec);//保存上述信息
//			    	lastDayTotal = value;//换新一天前，plc的读数总数
//			        }
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				logger.info("[ScheduleService][schedule2] e:", e);
//			}
	    }
		
		@Scheduled(fixedRate=86400000)
	    public void deleteDataSchedule() {
			// 数据库URL,根据具体情况更换
			String url = "jdbc:mysql://110.40.229.124:3306/forkliftv2";
	        // 数据库用户名，根据具体情况更换
	        String user = "forklift";
	        // 数据库密码，根据具体情况更换
	        String password = "123456";
			Calendar now = Calendar.getInstance();
			now.add(Calendar.YEAR, -1);
	        Date oneYearAgo = now.getTime();
	        String sql1 = "DELETE FROM tbl_energyrec WHERE createTime > #{oneYearAgo}";
	        try (Connection conn = DriverManager.getConnection(url, user, password);
	                PreparedStatement pstmt1 = conn.prepareStatement(sql1);
	               ) {

	               // 设置SQL语句中的参数
	               pstmt1.setDate(1, new java.sql.Date(oneYearAgo.getTime()));
	             
	               // 执行SQL语句
	               int rowsDeleted1 = pstmt1.executeUpdate();
	               logger.debug("[ScheduleService][deleteDataSchedule] rowsDeleted1:{}", rowsDeleted1);
	           } catch (SQLException e) {
	        	   logger.error("[ScheduleService][deleteDataSchedule] e:", e);
	           }
		}
//	
//	@Scheduled(fixedDelay=5000)
//    public void schedule3() {
//    	//test
//    }
	
}
